package com.zhumo.sz.service.impl;

import com.zhumo.sz.common.CommonInsert;
import com.zhumo.sz.common.CustomLogServerConfig;
import com.zhumo.sz.common.annotation.TransientSink;
import com.zhumo.sz.common.easyexcel.EasyExcelReader;
import com.zhumo.sz.common.utils.DateFormatUtil;
import com.zhumo.sz.entity.area.BaseArea;
import com.zhumo.sz.entity.road.*;
import com.zhumo.sz.entity.user.UserInfo;
import com.zhumo.sz.gaode.GaoDeAddressProcessor;
import com.zhumo.sz.gaode.GaoDeCityRoad;
import com.zhumo.sz.gaode.GaoDeGeoArea;
import com.zhumo.sz.gaode.GaoDeRoadProcessor;
import com.zhumo.sz.mapper.PublicMapper;
import com.zhumo.sz.mapper.RoadMapper;
import com.zhumo.sz.mapper.UserMapper;
import com.zhumo.sz.mock.RandomGenerator;
import com.zhumo.sz.mock.TrafficMocker;
import com.zhumo.sz.service.RoadService;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.util.*;

@Service
public class RoadServiceImpl implements RoadService {

    @Autowired
    private RoadMapper roadMapper;

    @Autowired
    private PublicMapper publicMapper;

    @Autowired
    private UserMapper userMapper;

    private static GaoDeAddressProcessor gaoDeAddressProcessor;

    /**
     * 初始化处理器
     */
    public static void InitProcessor() {
        if (gaoDeAddressProcessor != null) {
            if (gaoDeAddressProcessor.getApplicationKey().length() != 32) {
                throw new IllegalArgumentException("高德应用key传递有误");
            }
        } else {
            //默认使用注册的应用key
            gaoDeAddressProcessor = new GaoDeAddressProcessor(CustomLogServerConfig.GaoDE_APPLICATION_KEY);
        }
    }

    /**
     * 增加城市公路信息  全量刷新
     *
     * @param flush
     * @return
     */
    @Override
    public CommonInsert<CityRoad> addCityRoad(boolean flush, String version) {
        if (flush) {
            roadMapper.clearCityRoad();
        }
        List<BaseArea> areaList = publicMapper.getAllArea();
        ArrayList<CityRoad> roadCollect = new ArrayList<>();
        String[] dic = {"东", "西"};
        String[] dic2 = {"南", "北"};
        GaoDeRoadProcessor gaoDeRoadProcessor = new GaoDeRoadProcessor("d4e5f719651859757fa03e09bbc5130b");
        List<GaoDeCityRoad> gaoDeRoadList = gaoDeRoadProcessor.process(gaoDeRoadProcessor.key);
        for (GaoDeCityRoad gaoDeCityRoad : gaoDeRoadList) {
            CityRoad cityRoad = new CityRoad();
            cityRoad.setRoadCode(gaoDeCityRoad.getGdId());
            cityRoad.setRoadName(gaoDeCityRoad.getName());
            cityRoad.setBuildYear(String.valueOf(RandomGenerator.getRandomYear(2010, 2020)));
            cityRoad.setDistrict(gaoDeCityRoad.getAdname());
            for (BaseArea baseArea : areaList) {
                if (baseArea.getDistrict().equals(cityRoad.getDistrict())) {
                    cityRoad.setDistrictId(baseArea.getIpwebDistrictCode());
                    break;
                }
            }
            cityRoad.setSideWalkArea((double) RandomGenerator.generateAppointNumber(8000, 100000));
            cityRoad.setSideWalkNum(RandomGenerator.generateAppointNumber(5, 20));
            cityRoad.setIsEnabled(true);
            cityRoad.setVersion(version);
            cityRoad.setTrafficLightNum(cityRoad.getSideWalkNum());
            cityRoad.setCreateTime(Timestamp.valueOf(DateFormatUtil.toYmdHms(System.currentTimeMillis())));
            cityRoad.setToward(new Random().nextInt() < 2 ? dic[0] + "-" + dic[1] : dic2[0] + "-" + dic2[1]);
            roadCollect.add(cityRoad);
        }
        int result = roadMapper.addCityRoad(roadCollect);
        return new CommonInsert<CityRoad>(roadCollect.size(), result);
    }


    @Override
    public CommonInsert<CityHighRoad> addCityHeightRoad(boolean flush) {
        if (flush) {
            roadMapper.clearHighCityRoad();
        }
        String fileName = "E:\\毕业\\code\\sz-bigdata\\data\\深圳高速公路信息.xlsx";  // 替换成实际的文件名
        List<HighRoadDataXls> easyExcelRoadList = EasyExcelReader.readAsList(HighRoadDataXls.class, fileName);
        ArrayList<CityHighRoad> cityHighRoaList = new ArrayList<>();
        for (HighRoadDataXls highRoadDataXls : easyExcelRoadList) {
            CityHighRoad cityHighRoad = new CityHighRoad();
            cityHighRoad.setRoadId(Integer.valueOf(highRoadDataXls.getId()));
//            cityHighRoad.setRoadId(RandomGenerator.generateAppointNumber(1,10000000));
            cityHighRoad.setBuildYear(String.valueOf(RandomGenerator.getRandomYear(2010, 2020)));
            cityHighRoad.setRoad(highRoadDataXls.getName());
            cityHighRoad.setMaxRow(3);
            cityHighRoad.setOpenYear(String.valueOf(Integer.parseInt(cityHighRoad.getBuildYear()) + 1));
            cityHighRoad.setCreateTime(Timestamp.valueOf(DateFormatUtil.toYmdHms(System.currentTimeMillis())));
            cityHighRoaList.add(cityHighRoad);
        }
//        cityHighRoaList.forEach(System.out::println);
        int result = roadMapper.addCityHighRoad(cityHighRoaList);
        return new CommonInsert<CityHighRoad>(cityHighRoaList.size(), result);
    }

    /**
     * 增加高速公路收费站信息
     *
     * @param flush   是否刷新
     * @param version 版本
     */
    @Override
    public CommonInsert<HighSpeedTollStation> addHighSpeedStations(boolean flush, String version) {
        String fileName = "E:\\毕业\\code\\sz-bigdata\\data\\深圳高速公路信息.xlsx";  // 替换成实际的文件名
        List<HighRoadDataXls> easyExcelRoadList = EasyExcelReader.readAsList(HighRoadDataXls.class, fileName);
        ArrayList<HighSpeedTollStation> stationList = new ArrayList<>();
        //获取站点信息
//        List<CityHighRoad> roadList = roadMapper.getAllHighRoads();
        HashSet<String> stationIdSet = new HashSet<>();
        for (HighRoadDataXls highRoadDataXls : easyExcelRoadList) {
            Field[] declaredFields = highRoadDataXls.getClass().getDeclaredFields();
            for (Field declaredField : declaredFields) {
                declaredField.setAccessible(true);
                if (declaredField.getAnnotation(TransientSink.class) == null) {
//                    HighSpeedTollStation station = new HighSpeedTollStation();
//                    try {
//                        station.setName(String.valueOf(declaredField.get(highRoadDataXls)));
//                    } catch (IllegalAccessException e) {
//                        e.printStackTrace();
//                    }
                    String name = null;
                    try {
                        name = String.valueOf(declaredField.get(highRoadDataXls));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                    if (Objects.nonNull(name) && !name.equals("") && !name.equals("null")) {
                        HighSpeedTollStation station = new HighSpeedTollStation();
                        station.setName(name);
                        station.setRoadCode(highRoadDataXls.getId());
                        while (true) {
                            String stationCode = RandomGenerator.generateRandomNumber(6);
                            if (!stationIdSet.contains(stationCode)) {
                                station.setStationCode(stationCode);
                                stationIdSet.add(stationCode);
                                break;
                            }
                        }
                        CityHighRoad roadInfo = roadMapper.getHighRoadBy(station.getRoadCode());
                        station.setOpenYear(roadInfo.getOpenYear());
                        station.setBuildYear(roadInfo.getBuildYear());
                        station.setEtcEnabled(true);
                        station.setRowNum(3);
                        station.setNum(RandomGenerator.generateAppointNumber(4, 10));
                        station.setEtcNum(station.getNum()); //全部支持
                        //获取收费站所在区域
                        InitProcessor();
                        GaoDeGeoArea gaoDeGeoArea = gaoDeAddressProcessor.processGeocoAddress("广东省深圳市" + station.getName(), "JSON");
//                    station.setDistrictId(gaoDeGeoArea.get);
                        station.setDistrict(gaoDeGeoArea.getDistrict());
                        station.setCreateTime(Timestamp.valueOf(DateFormatUtil.toYmdHms(System.currentTimeMillis())));
                        stationList.add(station);
                    }
                }
            }
        }
        int result = roadMapper.addHighRoadStation(stationList);
        return new CommonInsert<HighSpeedTollStation>(stationList.size(), result);
    }


    /**
     * etc 进站
     *
     * @param flush
     * @param date
     * @param type
     * @return
     */
    @Override
    public CommonInsert<CityExpresswayEtcDetail> addEtcOrder(boolean flush, String date, String type, int num) {
        //执行查询 获取所有高速公路收费站
        List<HighSpeedTollStation> stationList = roadMapper.getAllHighRoadStations();
        if (Objects.isNull(type) || (!type.equals("batch") && !type.equals("realtime"))) {
            throw new IllegalArgumentException("数据参数传递异常");
        }
        if (flush) {
            roadMapper.clearEtc();
        }

        ArrayList<CityExpresswayEtcDetail> etcDataCollect = new ArrayList<>();
        HashSet<Long> dataKeySet = new HashSet<>();
        List<UserInfo> userInfoList = userMapper.sampleUser(num + 10);
        HashSet<String> cardSet = new HashSet<>();
        HashSet<String> carSet = new HashSet<>();
        for (int i = 0; i < num; i++) {
            CityExpresswayEtcDetail cityExpresswayEtcDetail = new CityExpresswayEtcDetail();
            while (true) {
                Long dataId = Long.parseLong(RandomGenerator.generateRandomNumber(15));
                if (!dataKeySet.contains(dataId)) {
                    cityExpresswayEtcDetail.setDataId(dataId);
                    dataKeySet.add(dataId);
                    break;
                }
            }
            //用户
            while (true) {
                UserInfo userInfo = userInfoList.get(new Random().nextInt(userInfoList.size()));
                if (!cardSet.contains(userInfo.getOneCard())) {
                    cardSet.add(userInfo.getOneCard());
                    cityExpresswayEtcDetail.setPeopleCard(userInfo.getOneCard());
                    break;
                }

            }
            //用户
            while (true) {
                String card = "粤B" + RandomGenerator.generateRandomString(5);
                if (!carSet.contains(card)) {
                    carSet.add(card);
                    cityExpresswayEtcDetail.setCard(card);
                    break;
                }
            }
            cityExpresswayEtcDetail.setNum(new Random().nextInt(4) + 1);
            HighSpeedTollStation startStationInfo = stationList.get(new Random().nextInt(stationList.size()));
            String startStationCode = startStationInfo.getStationCode();
            cityExpresswayEtcDetail.setStartStationCode(startStationCode);
            cityExpresswayEtcDetail.setStartRoadCode(startStationInfo.getRoadCode());
            //出口id.m,.;././
            Integer etcNum = startStationInfo.getEtcNum();
            cityExpresswayEtcDetail.setStartSiteCode(new Random().nextInt(etcNum) + 1);
            HighSpeedTollStation endStationInfo = null;
            while (true) {
                endStationInfo = stationList.get(new Random().nextInt(stationList.size()));
                if (!endStationInfo.getStationCode().equals(startStationCode)) {
                    cityExpresswayEtcDetail.setEndStationCode(endStationInfo.getStationCode());
                    cityExpresswayEtcDetail.setEndRoadCode(endStationInfo.getRoadCode());
                    //收费站通道编码
                    Integer endEtcNum = endStationInfo.getEtcNum();
                    cityExpresswayEtcDetail.setEndSiteCode(new Random().nextInt(endEtcNum) + 1);
                    break;
                }
            }
            String endTime = null;
            if (type.equals("batch")) {
                endTime = RandomGenerator.generateRandomTimeStamp(date);
            } else {
                endTime = DateFormatUtil.toYmdHms(System.currentTimeMillis());
            }
            cityExpresswayEtcDetail.setEndTime(Timestamp.valueOf(endTime));
            //获取地区 如果是同区域则
            if (Objects.nonNull(startStationInfo.getDistrict()) &&
                    !startStationInfo.getDistrict().equals(endStationInfo.getDistrict())) {
                //异区
                cityExpresswayEtcDetail.setStartTime(Timestamp.valueOf(
                        RandomGenerator.generateStartTime(endTime, -1 * (new Random().nextInt(21) + 20) * 60)
                ));
            } else { //同线高速通行时间
                cityExpresswayEtcDetail.setStartTime(Timestamp.valueOf(
                        RandomGenerator.generateStartTime(endTime, -1 * (new Random().nextInt(15) + 16) * 60)
                ));
            }
            cityExpresswayEtcDetail.setInTime((double) (new Random().nextInt(10) + 5));
            cityExpresswayEtcDetail.setOutTime((double) (new Random().nextInt(10) + 5));
            cityExpresswayEtcDetail.setCreateTime(cityExpresswayEtcDetail.getEndTime());
            etcDataCollect.add(cityExpresswayEtcDetail);
        }
        int result = roadMapper.addEtcData(etcDataCollect);
        return new CommonInsert<CityExpresswayEtcDetail>(etcDataCollect.size(), result);
    }


    /**
     * 城市区间测速每日明细表
     *
     * @param flush
     * @param type
     * @return
     */
    @Override
    public CommonInsert<RoadVelocityDetail> addVelocitys(boolean flush, String date, String type, int num) {
        ArrayList<RoadVelocityDetail> roadVelocityCollect = new ArrayList<>();
        if (Objects.isNull(type) || (!type.equals("batch") && !type.equals("realtime"))) {
            throw new IllegalArgumentException("参数传递异常");
        }
        if (flush) {
            roadMapper.clearVelocity();
        }
        List<CityRoad> roadList = roadMapper.getAllRoad();
        if (num >= roadList.size()) {
            throw new IllegalArgumentException("数量大于城市道路总量");
        }
        HashSet<Long> dataSet = new HashSet<>();
        HashSet<String> roadSet = new HashSet<>();
        for (CityRoad cityRoad : roadList) {
            RoadVelocityDetail roadVelocityDetail = new RoadVelocityDetail();
            // 获取id
            while (true) {
                long dataId = Long.parseLong(RandomGenerator.generateRandomNumber(15));
                if (!dataSet.contains(dataId)) {
                    roadVelocityDetail.setDataId(dataId);
                    dataSet.add(dataId);
                    break;
                }
            }
            //获取道路
            String roadCode = cityRoad.getRoadCode();
            roadVelocityDetail.setRoadCode(roadCode);
            roadVelocityDetail.setRoadType(cityRoad.getRoadType());
            try {
                String[] towardArray = cityRoad.getToward().split("-");
                if (towardArray.length < 2) {
                    roadVelocityDetail.setDirname(null);
                } else {
                    roadVelocityDetail.setDirname(towardArray[new Random().nextInt(towardArray.length)]);
                }
            } catch (Exception e) {
                e.printStackTrace();
                roadVelocityDetail.setDirname(null);
            }
            roadVelocityDetail.setIsLight(TrafficMocker.isLight());
            if (roadVelocityDetail.getIsLight()) {
                roadVelocityDetail.setLightWaitTime(RandomGenerator.generateAppointNumber(30, 100)); //红绿灯等待时长
            }
            roadSet.add(roadCode);

            roadVelocityDetail.setCarNum(RandomGenerator.generateAppointNumber(100, 1000));
            if (roadVelocityDetail.getCarNum() < 300) {
                roadVelocityDetail.setDistance(500.0);
            } else {
                roadVelocityDetail.setDistance(1000.0);
            }
            if (type.equals("batch")) {
                roadVelocityDetail.setEndTimestamp(Timestamp.valueOf(RandomGenerator.generateRandomTimeStamp(date)).getTime());
            } else {
                roadVelocityDetail.setEndTimestamp(Timestamp.valueOf(DateFormatUtil.toYmdHms(System.currentTimeMillis())).getTime());
            }
            //起始时间 5 - 10分钟
            int min = (new Random().nextInt(6)) + 5;
            roadVelocityDetail.setStartTimestamp(
                    Timestamp.valueOf(RandomGenerator.generateStartTime(
                            DateFormatUtil.toYmdHms(roadVelocityDetail.getEndTimestamp()), (-1 * min))
                    ).getTime());
            roadVelocityDetail.setCreateTime(Timestamp.valueOf(RandomGenerator.generateStartTime(
                    DateFormatUtil.toYmdHms(roadVelocityDetail.getEndTimestamp()), -1)));
            System.out.println(roadVelocityDetail);
            roadVelocityCollect.add(roadVelocityDetail);
        }
        int result = roadMapper.addRoadVelocity(roadVelocityCollect);
        return new CommonInsert<RoadVelocityDetail>(roadVelocityCollect.size(), result);
    }


}
